package org.example;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}


    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            //1.求出需要逆序的n组
            int n = 0;
            ListNode cur = head;
            while(cur != null) {
                n++;
                cur = cur.next;
            }
            n /= k;
            ListNode dummy = new ListNode(-1);
            ListNode tail = dummy;
            cur = head;//重置cur指向head
            //2.重复n次逆序,长度为k的链表即可
            while(n-- > 0){
                ListNode tmp = cur;//记录每次翻转之前的原始头结点
                //进行n次翻转链表的操作
                for (int i = 0; i < k; i++) {
                    //每次操作k个节点
                    ListNode next = cur.next;
                    cur.next = tail.next;
                    tail.next = cur;
                    cur = next;
                }
                tail = tmp;
            }
            //连接最后剩余的节点
            tail.next = cur;
            return dummy.next;
        }
    }